﻿using BZ.Logger;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Motion.MachineResources;
using NDK.Motion.StationLogic;
using NDK.Motion.Sys;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace NDK.Module.StationLogic
{
    /// <summary>
    /// 继承工站抽象类，根据需求可重写相关函数
    /// </summary>
    public abstract class StationLogicBase : StationLogicAbstract
    {
        string _cyErrMsg;
        public string CyErrMsg
        {
            get { return _cyErrMsg + " 气缸动作超时，请检查！"; }
            set { _cyErrMsg = value; }
        }

        string _vcErrMsg;
        public string VcErrMsg
        {
            get { return _vcErrMsg + " 真空负压值未达到，请检查！"; }
            set { _vcErrMsg = value; }
        }

        protected DateTime dtCt = DateTime.Now;

        protected Model.Quebec.ReturnProtocol findItem = null;
        protected string logBaseInfo = string.Empty;

        public const string CyTimeOutSolution = "\n1.检查气缸是否动作\n2.检查传感器\n3.检查接线";
        public const string CyOkTip = "点击OK按钮尝试继续运行";
        public const string CyCancelTip = "点击Cancel按钮忽略此报警继续运行[需确保安全]";

        public const string VcTimeOutSolution = "\n1.检查物料是否放平放正\n2.是否有负压，气管是否堵塞\n3.检查接线";
        public const string VcOkTip = "点击OK按钮尝试继续运行";
        public const string VcCancelTip = "点击Cancel按钮忽略此报警继续运行[需确保安全]";

        

        public bool cyRes = false;
        public bool axRes = false;
        public bool lightRes = false;
        public NDK.Motion.ImageLights.RES lightRES = new Motion.ImageLights.RES();

        public List<OutputSetting> ListVacuum;

        public List<ICylinder> ListCylinder;
     
        public ICylinder Cylinder;

        public bool camRes = false;

        public enum ROTOR_ACTION
        {
            NONE,
            PRE_LOAD,
            LOAD,
            PRE_MEASURE,
            MEASURE,
            STARTMEASURE,
            MEASUREDONE,
            PRE_UNLOAD,
            UNLOAD,
        }
        public enum ROTOR_POS
        {
            NONE,
            LOAD,
            MEASURE,
            MEASUREDONE,
            UNLOAD,
        }

        public bool CheckPosSafe(Position pos, string axisName)
        {
            try
            {
                return true;
                Axis axis = pos.AxisList.Find(x => x.Name == axisName);
                var vp = pos.VelocityProfiles.Find(x => x.AxisId == axis.AxisID);
                double curPos = axis.GetPos();
                if (Math.Abs(curPos - vp.Pos) > (axis.ErrBand + 10))
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
        /// <summary>
        /// 等待指定di状态为指定的状态，若超时时间内状态未达到，则返回false，正常等到状态，则返回true
        /// </summary>
        /// <param name="di"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        protected bool WaitDi(InputSetting di, int timeout = 3000)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            while (!di.GetStatus())
            {
                Thread.Sleep(10);
                if (sw.Elapsed.TotalMilliseconds > timeout) return false;
            }
            return true;
        }

        protected string CT(DateTime dt_start)
        {
            return $"[CT]->{(DateTime.Now - dt_start).TotalSeconds.ToString("0.000")}s";
        }

        protected void WriteInferenceCT(string dir, string item, string res, string ct)
        {
            var path = Path.Combine(dir, "InferenceCT.txt");
            using (var sw = new StreamWriter(path))
            {
                sw.WriteLine($"item -> {res} -> {ct}");
            }
        }

        object obj = new object();
        /// <summary>
        /// 机台报警暂停
        /// </summary>
        /// <param name="title">弹框报警的标题</param>
        /// <param name="exMsg">异常信息</param>
        /// <param name="exSolution">可能的异常原因,及解决方案</param>
        /// <param name="okOperationTip">点击OK的操作意义</param>
        /// <param name="cancelOperationTip">点击Cancel的操作意义</param>
        /// <returns>返回用户操作结果</returns>
        protected override DialogResult AlarmPause(string title, string excMsg, string exSolution, string okOperationTip, string cancelOperationTip)
        {
            lock (obj)
            {
                DialogResult dr;
                bool IsStatus = true;
                if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Alarm)
                    IsStatus = false;

                Common.AppendUiLog.Log(excMsg + exSolution, LogType.Error);

                if (IsStatus)
                {
                    MachineStatusManager.strDataAlarm = title;
                    MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;

                    DateTime startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                    dr = MessageBox.Show(excMsg + Environment.NewLine
                        + "【原因(解决方案)】" + exSolution + Environment.NewLine
                        + "【确定】" + okOperationTip + Environment.NewLine
                        + "【取消】" + cancelOperationTip, title, MessageBoxButtons.OKCancel);

                    if (dr == DialogResult.OK)
                    {
                        excMsg += ",点击【确定】" + okOperationTip;
                    }
                    else
                    {
                        excMsg += ",点击【取消】" + cancelOperationTip;
                    }


                    DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                    int timeCount = (endTime - startTime).Seconds;

                    AlarmInfo alarmInfo = new AlarmInfo()
                    {
                        StartTime = startTime,
                        EndTime = endTime,
                        TimeCount = timeCount,
                        Type = title,
                        Description = excMsg
                    };
                    AlarmInfoServices AlarmInfoServices = new AlarmInfoServices();
                    AlarmInfoServices.Add(alarmInfo);
                }
                else
                    dr = DialogResult.OK;
                return dr;
            }
        }
        protected override DialogResult AlarmPause(string title, string excMsg, string exSolution, string okOperationTip)
        {
            bool IsStatus = true;
            if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Alarm)
                IsStatus = false;
            Common.AppendUiLog.Log(excMsg + exSolution, LogType.Error);
            DialogResult dr;
            if (IsStatus)
            {
                MachineStatusManager.strDataAlarm = title;
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;

                DateTime startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                dr = MessageBox.Show(excMsg + Environment.NewLine
                  + "【原因(解决方案)】" + exSolution + Environment.NewLine
                  + "【确定】" + okOperationTip + Environment.NewLine,
                  title, MessageBoxButtons.OK);

                if (dr == DialogResult.OK)
                {
                    excMsg += ",点击【确定】" + okOperationTip;
                }

                DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                int timeCount = (endTime - startTime).Seconds;

                AlarmInfo alarmInfo = new AlarmInfo()
                {
                    StartTime = startTime,
                    EndTime = endTime,
                    TimeCount = timeCount,
                    Type = title,
                    Description = excMsg
                };
                AlarmInfoServices AlarmInfoServices = new AlarmInfoServices();
                AlarmInfoServices.Add(alarmInfo);
            }
            else
                dr = DialogResult.OK;
            return dr;
        }
        protected override DialogResult AlarmPause(string title, string excMsg, string exSolution, string yesOperationTip, string noOperationTip, string cancelOperationTip)
        {
            bool IsStatus = true;
            if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Alarm)
                IsStatus = false;
            DialogResult dr;
            Common.AppendUiLog.Log(excMsg + exSolution, LogType.Error);
            if (IsStatus)
            {
                MachineStatusManager.strDataAlarm = title;
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                DateTime startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                dr = MessageBox.Show(excMsg + Environment.NewLine
                   + "【原因(解决方案)】" + exSolution + Environment.NewLine
                   + "【是】" + yesOperationTip + Environment.NewLine
                   + "【否】" + noOperationTip + Environment.NewLine
                   + "【取消】" + cancelOperationTip,
                   title, MessageBoxButtons.YesNoCancel);

                if (dr == DialogResult.Yes)
                {
                    excMsg += ",点击【是】" + yesOperationTip;
                }
                else if (dr == DialogResult.No)
                {
                    excMsg += ",点击【否】" + noOperationTip;
                }
                else
                {
                    excMsg += ",点击【取消】" + cancelOperationTip;
                }

                DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                int timeCount = (endTime - startTime).Seconds;

                AlarmInfo alarmInfo = new AlarmInfo()
                {
                    StartTime = startTime,
                    EndTime = endTime,
                    TimeCount = timeCount,
                    Type = title,
                    Description = excMsg
                };

                AlarmInfoServices AlarmInfoServices = new AlarmInfoServices();
                AlarmInfoServices.Add(alarmInfo);
            }
            else
                dr = DialogResult.Yes;
            return dr;
        }

        protected void UILog_Info(string mes)
        {
            Common.AppendUiLog.Log(mes, LogType.Info);
        }
        protected void UILog_Alert(string mes)
        {
            Common.AppendUiLog.Log(mes, LogType.Alert);
        }
        protected void UILog_Error(string mes)
        {
            Common.AppendUiLog.Log(mes, LogType.Error);
        }

    }
}
